package org.sg20.graphbuilder;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import java.io.IOException;


public class gx {
    public static class gxmap extends Mapper<LongWritable, Text, Text, IntWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] split = value.toString().split("\t");
            Text text = new Text(split[0]);
            IntWritable intWritable = new IntWritable(Integer.valueOf(split[1]));
            context.write(text,intWritable);
        }
    }
    private static class gxreduce extends Reducer<Text,IntWritable,Text,IntWritable> {
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum=0;
            for (IntWritable i : values) {
                sum+=i.get();
            }
            IntWritable intWritable = new IntWritable(sum);
            context.write(key,intWritable);
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();

        //Parse arguments
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length != 2) {
            System.err.println("Please input: xxx.jar gx  [InputPath] [OutputPath].");
            System.exit(1);
        }

        Job job = Job.getInstance(conf, "gx");



        job.setJarByClass(gx.class);

        job.setMapperClass(gxmap.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setReducerClass(gxreduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        String outPath = otherArgs[1]+"/Combine";


        FileInputFormat.setInputPaths(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(outPath));
        FileSystem fs = FileSystem.get(new Configuration());

        if (fs.exists(new Path(outPath))){
            fs.delete(new Path(outPath),true);
        }
        boolean b = job.waitForCompletion(true);
        System.exit(b ? 0 : 1);
    }
}
